//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.carhailing.system.service.Impl;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carhailing.common.domain.DriverUser;
import com.carhailing.common.requst.DriverUserReq;
import com.carhailing.common.response.JwtResponse;
import com.carhailing.common.result.Result;
import com.carhailing.common.utils.JwtUtils;
import com.carhailing.system.mapper.DriverUserMapper;
import com.carhailing.system.service.DriverUserService;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class DriverUserServiceImpl extends ServiceImpl<DriverUserMapper, DriverUser> implements DriverUserService {
    private static final Logger log = LogManager.getLogger(DriverUserServiceImpl.class);
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private HttpServletRequest request;

    public DriverUserServiceImpl() {
    }

    public Result sendCode(String phone) {
        DriverUser driverUsers = this.selectdriverUser(phone);
        if (null == driverUsers) {
            return Result.error("手机号不存在");
        } else if (!Validator.isMobile(phone)) {
            return Result.error("手机号不合法");
        } else {
            String code = RandomUtil.randomNumbers(4);
            if (this.redisTemplate.hasKey(phone)) {
                Long count = this.redisTemplate.opsForValue().increment(phone, 1L);
                if (count >= 3L) {
                    return Result.error("发送验证码次数过多，请稍后再试");
                }

                this.redisTemplate.expire(phone, 24L, TimeUnit.HOURS);
            } else {
                this.redisTemplate.opsForValue().set(phone, "1", 24L, TimeUnit.HOURS);
            }

            this.redisTemplate.opsForValue().set("send_sms_" + phone, code, 1L, TimeUnit.MINUTES);
            StrFormatter.format("您的验证码是：{{}}，有效期一分钟", new Object[]{code});
            log.info("发送验证码的内容是：" + code);
            DriverUserReq userReq = new DriverUserReq();
            userReq.setDriverPhone(phone);
            userReq.setCode(code);
            this.rabbitTemplate.convertAndSend("SEND_SMS", userReq, (message) -> {
                String messageId = IdUtil.randomUUID().replace("-", "");
                message.getMessageProperties().setMessageId(messageId);
                return message;
            });
            return Result.success(code);
        }
    }

    public Result login(DriverUserReq userReq) {
        DriverUser driverUsers = this.selectdriverUser(userReq.getDriverPhone());
        if (null == driverUsers) {
            return Result.error("手机号不存在");
        } else if (!Validator.isMobile(userReq.getDriverPhone())) {
            return Result.error("手机号不合法");
        } else if (!this.redisTemplate.hasKey(userReq.getDriverPhone())) {
            return Result.error("验证码已过期");
        } else if (!((String)this.redisTemplate.opsForValue().get("send_sms_" + userReq.getDriverPhone())).equals(userReq.getCode())) {
            return Result.error("验证码错误");
        } else {
            String userKey = UUID.randomUUID().toString();
            HashMap<String, Object> map = new HashMap();
            map.put("user_key", userKey);
            String token = JwtUtils.createToken(map);
            this.redisTemplate.opsForValue().set("login_tokens:" + userKey, JSON.toJSONString(driverUsers), 30L, TimeUnit.MINUTES);
            JwtResponse jwtResponse = new JwtResponse();
            jwtResponse.setTimeStr("720MIN");
            jwtResponse.setToken(token);
            return Result.success(jwtResponse);
        }
    }

    public DriverUser DriverUserInfo() {
        String token = this.request.getHeader("token");
        String userKey = JwtUtils.getUserKey(token);
        String s = (String)this.redisTemplate.opsForValue().get("login_tokens:" + userKey);
        return (DriverUser)JSONObject.parseObject(s, DriverUser.class);
    }

    private DriverUser selectdriverUser(String driverPhone) {
        QueryWrapper<DriverUser> wrapper = (QueryWrapper)(new QueryWrapper()).eq("driver_phone", driverPhone);
        return (DriverUser)((DriverUserMapper)this.baseMapper).selectOne(wrapper);
    }
}
